﻿//////////////////////////////////////////////////////////////////
//
// ScriptFile.cs
//
// Copyright (c) 2012 Dan Pike.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using Antlr.Runtime;
using Antlr.Runtime.Tree;
using Antlr3.ST;
using Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Utilities;

namespace ScriptANTLR
{
   public class ScriptFile : IScriptFile
   {
      private Logger logger_;
      private string displayName_;
      private string filename_;

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// 
      /// </summary>
      public ScriptFile()
      {
         logger_ = Program.logger;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool compile(string filename)
      {
         try
         {
            filename_ = filename;
            logger_.debugFormat("compiling script file '{0}'", filename_);

            // The lexical analysis will output a stream of tokens
            CommonTokenStream tokens = prepareLexer();
            if (null == tokens)
            {
               return false;
            }

            // Phase 1 of the parsing produces an AST
            // Phase One - create the AST
            KeyValuePair<CommonTree, string> parserResult = phaseOneParser(tokens);
            if (null == parserResult.Key)
            {
               return false;
            }
            displayName = parserResult.Value;

            // Phase Two - walk the tree and output the code
            if (!phaseTwoWalker(parserResult.Key, tokens))
            {
               return false;
            }

            logger_.debugFormat("script file '{0}' compiled OK", filename_);
            return true;
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Run the lexer on the script file to produce a token stream
      /// </summary>
      private CommonTokenStream prepareLexer()
      {
         CommonTokenStream tokens = null;
         try
         {
            FileStream stream = new FileStream(filename_, FileMode.Open, FileAccess.Read,
               FileShare.Read, 16384, FileOptions.SequentialScan);
            ANTLRInputStream input = new ANTLRInputStream(stream);
            PhaseOneLexer lexer = new PhaseOneLexer(input);
            tokens = new CommonTokenStream(lexer);
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return tokens;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Parse the token stream and produce an AST
      /// </summary>
      private KeyValuePair<CommonTree, string> phaseOneParser(CommonTokenStream tokens)
      {
         KeyValuePair<CommonTree, string> result = new KeyValuePair<CommonTree, string>(null, null);
         try
         {
            PhaseOneParser parser = new PhaseOneParser(tokens);
            AstParserRuleReturnScope<CommonTree, CommonToken> parserResult = parser.scriptFile();
            result = new KeyValuePair<CommonTree, string>(parserResult.Tree, parser.displayName);
            logger_.debugFormat("built tree: {0}", result.Key.ToStringTree());
         }
         catch (RecognitionException ex)
         {
            logger_.exception("\n{0}({1}): unexpected token '{2}' around character #{3}", ex,
               filename_, ex.Line, ex.Token.Text, ex.CharPositionInLine);
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return result;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Walk the AST and output the IL to our type
      /// </summary>
      private bool phaseTwoWalker(CommonTree tree, CommonTokenStream tokens)
      {
         try
         {
            CommonTreeNodeStream nodes = new CommonTreeNodeStream(tree);
            nodes.TokenStream = tokens;
            PhaseTwo walker = new PhaseTwo(nodes);
            walker.scriptFile = this;
            walker.scriptAST();
            return true;
         }
         catch (RecognitionException ex)
         {
            logger_.exception("unexpected token '{0}' (#{1}) in tree produced from file '{2}'\n", ex,
               ex.Token.Text, ex.Token.TokenIndex, filename_);
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public object initialize(object entity)
      {
         try
         {
            logger_.debugFormat("constructing runner for script file '{0}'", filename_);
         }
         catch (System.Exception ex)
         {
            logger_.exception(ex);
         }
         return null;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public bool run(object runner, string methodName, object[] parameters)
      {
         try
         {
            return true;
         }
         catch (System.Exception ex)
         {
            logger_.exception("running method '{0}' in script file '{1}", ex, methodName, filename_);
         }
         return false;
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// Implementation of IScriptFile
      /// </summary>
      public string displayName
      {
         get { return displayName_; }
         set { displayName_ = value; }
      }

      ////////////////////////////////////////////////////////////////////////
      /// <summary>
      /// The file containing the script source
      /// </summary>
      public string filename
      {
         get { return filename_; }
         set { filename_ = value; }
      }
   }
}
